// ignore_for_file: unused_import
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper/components/placeholder/avatar.dart';
import 'package:wallpaper/components/input/normal_input.dart';
import 'package:wallpaper/components/my_tab_header.dart';
import 'package:wallpaper/components/my_tab_scroll_header.dart';
import 'package:wallpaper/generated/l10n.dart';
import 'package:wallpaper/model/SliverTabBarDelegate.dart';
import 'package:wallpaper/pages/other/wallhaven/filter_items.dart';
import 'package:wallpaper/pages/navbar/child/mobile_home.dart';
import 'package:wallpaper/pages/other/wallhaven/wallhaven_list.dart';
import 'package:wallpaper/pages/other/search/search_image.dart';
import 'package:wallpaper/providers/setting_provider.dart';
import 'package:wallpaper/tools/down_image.dart';
import 'package:wallpaper/tools/route_animation.dart';
import 'package:wallpaper/tools/update_apk.dart';
import 'dart:math' as math;

class WallhavenPage extends StatefulWidget {
  const WallhavenPage({super.key});

  @override
  State<WallhavenPage> createState() => _WallhavenPageState();
}

class _WallhavenPageState extends State<WallhavenPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  final PageController _pageController = PageController();
  final ScrollController _scrollController = ScrollController();
  TextEditingController controller = TextEditingController();
  bool change = true;
  final List<String> subList = ['最新', '热门', '随机', '浏览', '收藏', '排行榜'];
  final List<String> types = [
    'date_added',
    'hot',
    'random',
    'views',
    'favorites',
    'toplist'
  ];

  // 筛选条件
  TextEditingController ratioController = TextEditingController();
  String ratio = ''; // 16x9
  String order = 'desc'; // desc or asc
  String categories = '111';
  String purity = '110';
  String customize = '110';
  String ratioSelected = '';
  final FocusNode _inputFocusNode = FocusNode();

  void changeOrder(String value) {
    setState(() {
      order = value;
    });
  }

  void changeRatioSelected(value) {
    if (value != null) {
      setState(() {
        ratioSelected = value;
        if (value == 'customize') {
          ratio = ratioController.text;
        } else {
          ratio = value;
        }
      });
    }
  }

  void changeCategories(value) {
    setState(() {
      categories = value;
    });
  }

  void changePurity(value) {
    setState(() {
      purity = value;
    });
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 6,
      vsync: this,
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _tabController.dispose();
    controller.dispose();
    ratioController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;

    final List<Widget> pages = [
      for (var i = 0; i < subList.length; i++)
        WallhavenList(
          type: types[i],
          q: controller.text,
          change: change,
          ratio: ratio,
          order: order,
          categories: categories,
          purity: purity,
          customize: customize,
        ),
    ];
    final topPadding = MediaQuery.of(context).padding.top;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      endDrawer: Drawer(
        width: 300,
        clipBehavior: Clip.antiAlias,
        // 设置圆角
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(0),
        ),
        backgroundColor: Colors.black.withOpacity(0.5),
        child: FilterItems(
          order: order,
          ratioSelected: ratioSelected,
          ratioController: ratioController,
          categories: categories,
          purity: purity,
          changeOrder: changeOrder,
          changeRatioSelected: changeRatioSelected,
          changeCategories: changeCategories,
          changePurity: changePurity,
          conditionalQuery: () {
            FocusScope.of(context).requestFocus(FocusNode());
            setState(() {
              change = !change;
            });
          },
        ),
      ),
      body: Column(
        children: [
          Container(
            // 顶部安全距离
            height: topPadding,
            color: theme.primaryContainer,
          ),
          _buildHeader(context, theme),
          MyTabScrollHeader(
            tabController: _tabController,
            tabs: subList,
            onTap: (index) {
              _pageController.jumpToPage(index);
            },
          ),
          Expanded(
            child: PageView(
              controller: _pageController,
              children: pages,
              onPageChanged: (index) {
                // 页面滑动时同步 Tab
                _tabController.animateTo(index);
              },
            ),
          )
        ],
      ),
    );
  }

  Widget _buildHeader(BuildContext context, ColorScheme theme) => Container(
        color: theme.primaryContainer,
        child: Row(
          spacing: 10,
          children: [
            Expanded(
              child: NormalInput(
                height: 34,
                controller: controller,
                focusNode: _inputFocusNode,
                onSubmitted: (text) {
                  setState(() {
                    change = !change;
                  });
                  _inputFocusNode.unfocus();
                },
              ),
            ),
            Builder(
              builder: (innerContext) {
                return IconButton(
                  onPressed: () {
                    // 使用 Builder 提供的 innerContext，而非外层的 context
                    Scaffold.of(innerContext).openEndDrawer();
                  },
                  icon: Icon(Icons.menu, color: theme.onSurface),
                  color: theme.onPrimaryContainer,
                  iconSize: 26,
                );
              },
            )
          ],
        ),
      );
}
